package com.njlime.sys.service;

import com.alibaba.fastjson.JSONObject;
import com.njlime.core.helper.quartz.QuartzManager;
import com.njlime.sys.entities.RegularTask;
import com.njlime.sys.repository.RegularTaskDao;
import org.quartz.JobDataMap;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 定时任务Service
 * Created by Dean on 2017-7-27.
 */
@Service
public class RegularTaskService {

    @Resource
    private RegularTaskDao regularTaskDao;

    /**
     * 添加定时任务
     * @param jobName 任务名称
     * @param jobClass 任务类路径
     * @param cron 执行时间
     * @param jobParam 任务参数
     */
    @Transactional
    public void addRegularTask(String jobName, Class jobClass, String cron, Map<String,Object> jobParam){
        RegularTask regularTask = new RegularTask();
        regularTask.setName(jobName);
        regularTask.setClazz(jobClass.getName());
        regularTask.setCreate_time(new Date());
        regularTask.setCron(cron);
        if(jobParam != null){
            regularTask.setParam(JSONObject.toJSONString(regularTask));
        }
        regularTask.setStatus(RegularTask.RegularTaskStatus.UN_EXECUTE);
        regularTaskDao.save(regularTask);
        JobDataMap jobDataMap = null;
        if(jobParam != null){
            jobDataMap = new JobDataMap(jobParam);
        }
        QuartzManager.addJob(jobName,jobClass,cron,jobDataMap);
    }

    /**
     * 更改定时任务时间
     * @param jobName
     * @param cron
     */
    @Transactional
    public void updateRegularTask(String jobName, String cron){
        RegularTask regularTask = regularTaskDao.getByJobName(jobName);
        regularTask.setCron(cron);
        regularTaskDao.save(regularTask);
        QuartzManager.modifyJobTime(jobName, cron);
    }

    /**
     * 移除定时任务
     * @param jobName
     */
    @Transactional
    public void removeRegularTask(String jobName){
        RegularTask regularTask = regularTaskDao.getByJobName(jobName);
        regularTaskDao.delete(regularTask.getId());
        QuartzManager.removeJob(jobName);
    }

    /**
     * 更改定时任务状态
     * @param jobName
     * @param status
     */
    @Transactional
    public void updateRegularTaskStatus(String jobName, Integer status){
        RegularTask regularTask = regularTaskDao.getByJobName(jobName);
        regularTask.setStatus(status);
        regularTask.setExec_time(new Date());
        regularTaskDao.save(regularTask);
    }

    public List<RegularTask> getJobList(){
        return regularTaskDao.getJobList();
    }



}
